#!/usr/bin/perl
# Extract the examples from the book text (.txt) into separate files.
# (copied from extract.pl and modified)

use strict;

my $suffix = ".txt";
my $usage = "use: extbook destdir file...\n";

my $destdir = shift @ARGV;
die $usage unless (-d $destdir);

my $fname;
for $fname (@ARGV)
{
	open FILE, "<", $fname
		or die "Can not open file '$fname' for reading: $!\n";

	my $inside = 0;
	my $exname;
	my %text;
	my $line = 0;
	while(<FILE>) {
		chomp;
		++$line;
		if ($inside) {
			if (/^\[\[end\]\]/) {
				$inside = 0;
				undef $exname;
			} elsif (/^\[\[(ex....)\]\]/) {
				die "Unterminated example '$exname' followed by '$1' on $fname line $line\n";
			} else {
				push @{$text{$exname}}, $_ if ($inside);
			}
		} else {
			if (/^\[\[end\]\]/) {
				die "A spurious [[end]] mark on $fname line $line\n";
			} elsif (/^\[\[(ex....)\]\]/) {
				$inside = 1;
				$exname=$1;
				die "Duplicate example '$exname' found on $fname line $line\n" if (exists $text{$exname});
				$text{$exname} = [];
				printf STDERR "Found example $exname in $fname at line $line\n"; # SBDBG
			}
		}
	}
	die "File '$fname' ends while in the middle of example '$exname'\n" if ($inside);

	close FILE;

	my $ex;
	foreach $ex (sort keys %text) {
		my $destf = $destdir . "/" . $ex . $suffix;
		die "The file '$destf' already exists, probably found in multiple sources\n"
			if (-f $destf);

		open RES, ">", $destf
			or die "Can not open file '$destf' for writing: $!\n";

		my $ot = $text{$ex}; # a reference
		my $tl;
		foreach $tl (@$ot) {
			print RES "$tl\n";
		}
		close RES
			or die "Can not write to file '$destf': $!\n";
	}
}
